package com.kanshu.ksgb.fastread.doudou.module.book.activity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.hz.yl.b.mian.CenBanner;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.basemvp.BaseMVPActivity;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdTimerHelper;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.BaseAdListener;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.ReaderAdHelper;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigs;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.NotifyBean;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ReaderFinishEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.CacheManager;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.common.business.pay.event.PayActionEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.IMakeMoneyService;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.BookUtils;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DiskLruCacheUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.RomUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.RxTimerUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.SystemBarUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.CustomDialog;
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.BookmarkAdapter;
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.ReadThemeAdapter;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.BookMark;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ReadTheme;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.SimpleChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.BookListPresenter;
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.BookPresenter;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.requestparams.ChapterRequestParams;
import com.kanshu.ksgb.fastread.doudou.module.reader.bean.BookRecordBean;
import com.kanshu.ksgb.fastread.doudou.module.reader.page.PageLoader;
import com.kanshu.ksgb.fastread.doudou.module.reader.page.PageMode;
import com.kanshu.ksgb.fastread.doudou.module.reader.page.PageStyle;
import com.kanshu.ksgb.fastread.doudou.module.reader.page.PageView;
import com.kanshu.ksgb.fastread.doudou.module.reader.page.TxtChapter;
import com.kanshu.ksgb.fastread.doudou.module.reader.presenter.ReadContract;
import com.kanshu.ksgb.fastread.doudou.module.reader.presenter.ReadPresenter;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.ObtainAllSimpleChaptersHelper;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.ReaderPopupWindowHelper;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.ScreenOnHelper;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.SettingManager;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.ThemeManager;
import com.kanshu.ksgb.fastread.doudou.module.reader.view.AdBetweenChaptersLayout;
import com.kanshu.ksgb.fastread.doudou.module.reader.view.BookReadBottomLayout;
import com.kanshu.ksgb.fastread.doudou.module.reader.view.BookReadErrorLayout;
import com.kanshu.ksgb.fastread.doudou.module.reader.view.BookReadErrorLayout.ReadErrCallback;
import com.kanshu.ksgb.fastread.doudou.module.reader.view.LastPageLabelLayout;
import com.kanshu.ksgb.fastread.doudou.module.reader.view.ReaderShareDialog;
import com.kanshu.ksgb.fastread.doudou.module.reader.view.VirtualKeyLayout;
import com.qmuiteam.qmui.util.QMUINotchHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

import static android.support.v4.view.ViewCompat.LAYER_TYPE_SOFTWARE;
import static com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils.gone;
import static com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils.isGone;
import static com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils.isVisible;
import static com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils.visible;
import static com.kanshu.ksgb.fastread.doudou.module.reader.page.PageMode.COVER;
import static com.kanshu.ksgb.fastread.doudou.module.reader.page.PageMode.NONE;
import static com.kanshu.ksgb.fastread.doudou.module.reader.page.PageMode.SCROLL;
import static com.kanshu.ksgb.fastread.doudou.module.reader.page.PageMode.SIMULATION;
import static com.kanshu.ksgb.fastread.doudou.module.reader.page.PageMode.SLIDE;

/**
 * 最新的书籍阅读器
 * Created by wcy
 */
public class AdBookReaderActivity extends BaseMVPActivity<ReadContract.Presenter>
        implements ReadContract.View, BaseAdListener {
    public static int ACTION_DESTORY = 9;
    // 广告容器高度   默认模式
    private static int MODE_AD_HEIGHT_DEFAULT = 1;
    // 广告容器高度   增高显示模式
    private static int MODE_AD_HEIGHT_HIGH = 2;
    // 外部传入参数
    public static final String EXTRA_BOOK_ID = "book_id";
    public static final String EXTRA_CHAPTER_ID = "content_id";
    public static final String EXTRA_CHAPTER_INDEX = "order";
    public static final String EXTRA_BOOK_NAME = "book_title";
    public static final String EXTRA_JUMP_TO_HOME = "jump_to_home";
    public static final String EXTRA_CONTINUE_READ = "continue_read";
    @BindView(R.id.root_view)
    VirtualKeyLayout mVirtualKeyLayout;
    @BindView(R.id.read_abl_top_menu)
    AppBarLayout mAblTopMenu;
    @BindView(R.id.read_pv_page)
    PageView mPvPage;
    @BindView(R.id.read_setting_rg_page_mode)
    RadioGroup mRgPageMode;
    @BindView(R.id.volume_switch_container)
    RadioGroup mVolumeSwitchContainer;
    @BindView(R.id.volume_open)
    RadioButton mVolumeOpen;
    @BindView(R.id.volume_close)
    RadioButton mVolumeClose;
    @BindView(R.id.llBookReadBottom)
    BookReadBottomLayout mLlBottomMenu;
    @BindView(R.id.seekbarLightness)
    SeekBar mSeekbarLightness;
    @BindView(R.id.cbAutoBrightness)
    CheckBox mCbAutoBrightness;
    @BindView(R.id.eye_shield)
    CheckBox mCbEyeShield;
    @BindView(R.id.gvTheme)
    GridView mGvTheme;
    @BindView(R.id.rlReadAaSet)
    LinearLayout mRlReadAaSet;
    @BindView(R.id.lvMark)
    ListView mLvMark;
    @BindView(R.id.rlReadMark)
    LinearLayout mRlReadMark;
    @BindView(R.id.read_progress_set)
    View mReadProgressSet;
    @BindView(R.id.read_brightness_set)
    View mReadBrightnessSet;
    @BindView(R.id.night_mode)
    CheckBox mNightMode;
    @BindView(R.id.reader_guide)
    View mReaderGuide;
    @BindView(R.id.font_result)
    TextView mFontSizeResult;
    @BindView(R.id.read_setting_rb_simulation)
    RadioButton mRbSimulation;
    @BindView(R.id.read_setting_rb_cover)
    RadioButton mRbCover;
    @BindView(R.id.read_setting_rb_slide)
    RadioButton mRbSlide;
    @BindView(R.id.read_setting_rb_none)
    RadioButton mRbNone;
    @BindView(R.id.more_entry)
    View mMoreEntry;
    @BindView(R.id.screen_on_always_container)
    RadioGroup mScreenOnAlways;
    @BindView(R.id.min_3)
    RadioButton mScreenOn3Min;
    @BindView(R.id.min_5)
    RadioButton mScreenOn5Min;
    @BindView(R.id.min_10)
    RadioButton mScreenOn10Min;
    @BindView(R.id.min_ofen)
    RadioButton mScreenOnOften;
    @BindView(R.id.eye_shield_layout)
    View mEyeShieldLayout;
    @BindView(R.id.chapter_progress_bar)
    SeekBar mChapterSeekbar;
    @BindView(R.id.chapter_progress_container)
    LinearLayout mChapterProgressContainer;
    @BindView(R.id.chapter_progress_name)
    TextView mChapterProgressName;
    @BindView(R.id.chapter_progress_txt)
    TextView mChapterProgressPercent;
    @BindView(R.id.adContainer)
    FrameLayout mAdContainer;
    @BindView(R.id.wrap_ad_container)
    FrameLayout mWrapAdContainer;
    @BindView(R.id.ad_banner_trans)
    View mAdBannerTrans;
    @BindView(R.id.root_reader_container)
    FrameLayout mRlBookReadRoot;
    AdBetweenChaptersLayout mAdBetweenChaptersLayout;
    private String mBookId;
    // 章节内容id
    private String mCurChapterId;
    // 是否需要连续阅读
    private boolean mContinueRead;
    // 开始阅读标记 如果为true说明会渲染页面
    private boolean mStartRead;
    private int mCurChapterIndex = 1;
    private String mBookTitle;
    private boolean mIsJumpToHome;
    // 是否第一次绘制文字信息
    private boolean mIsFirstRender;
    Subject<Integer> mLifeCyclerSubject = PublishSubject.create();
    // 章节内容请求参数
    ChapterRequestParams mParams = new ChapterRequestParams();
    // 广告配置
    private ADConfigBean mShowAD;
    // 广告高度
    private int mAdHeight = 0;
    private int mScreenHeight;
    private int mScreenWidth;
    // 广告是否加载成功  才showAD  默认设置为true  是为了第一次广告加载失败回调时可以关闭广告显示
    private boolean mLoadSuccShowAd = true;
    // 主题色适配器
    ReadThemeAdapter gvAdapter;
    // 当前主题
    private int mCurTheme;
    // 主题列表
    List<ReadTheme> mReadThemes;
    // 书签适配器
    BookmarkAdapter mMarkAdapter;
    // 书签列表
    List<BookMark> mMarkList = new ArrayList<>();
    // 阅读器夜间模式变量
    private boolean isNightMode = false;
    // 亮度监听器
    private ContentObserver mLightnessObserver;
    private SafeHandler mHandler;
    // 阅读器分页管理器
    private PageLoader mPageLoader;
    // 用于阅读器上报阅读记录
    private BookListPresenter mListPresenter;
    // 屏幕常亮工具类
    private ScreenOnHelper mScreenOnHelper;
    // 点击记录时间戳
    private static long sClickTime1 = 0L;
    //阅读器视频播放辅助类
    public ReaderAdHelper mReaderAdHelper;
    // 错误处理页面
    private BookReadErrorLayout mErrorLayout;
    // 判断是否后台记录了已经加入书架
    private boolean mJoinShelfFromServer;
    private long mOldTime = 0;
    private String mCurrentChapterPos = "";
    // 当前章节内容页数
    private int mCurrentChapterCount;
    // 章节进度 监听 章节内容页数;
    private int mSeekbarListenerPageCount;
    private int mCurrentAdHeightMode;   // 当前广告高度模式

    // 接收电池信息和时间更新的广播
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        private int mOldBattery = 0;  // 旧的电量信息

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
                int level = intent.getIntExtra("level", 0);
                if (Math.abs(mOldBattery - level) > 4 || level == 100) { // 电量改变超过5% 才刷新一次
                    mOldBattery = level;
                    if (mPageLoader != null) {
                        mPageLoader.updateBattery(level);
                    }
                }
            }
            // 监听分钟的变化
            else if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                mPageLoader.updateTime();
            } else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                // 监听网络状况

            }
        }
    };
    /********** banner广告 ***************/
    private int mAdPositionId = ADConfigBean.POSITION_BOOK_READER_BOTTOM;
    private boolean isFetchBannerAd = true;
    private AdTimerHelper mAdTimerHelper = new AdTimerHelper(this::getAdBanner);
    private LastPageLabelLayout mLastPageLabelLayout;//尾页摇一摇

    /**
     * 解析外部传入的参数
     */
    private void parseIntent() {
        String bookId = mBookId;
        mBookId = getIntent().getStringExtra(EXTRA_BOOK_ID);
        boolean flg = !TextUtils.isEmpty(bookId) && !TextUtils.equals(bookId, mBookId);
        // 标记前后不是一本书
        if (flg) {
            resetBookId();
        }
        // mCurChapterId为空则是第一个章节获取内容
        mCurChapterId = getIntent().getStringExtra(EXTRA_CHAPTER_ID);
        String order = getIntent().getStringExtra(EXTRA_CHAPTER_INDEX);
        if (!TextUtils.isEmpty(order)) {
            mCurChapterIndex = Integer.parseInt(order);
        } else {
            mCurChapterIndex = 0;
        }
        mBookTitle = getIntent().getStringExtra(EXTRA_BOOK_NAME);
        String isJumpHome = getIntent().getStringExtra(EXTRA_JUMP_TO_HOME);
        if (!TextUtils.isEmpty(isJumpHome)) {
            mIsJumpToHome = Boolean.parseBoolean(isJumpHome);
        }
        if (TextUtils.isEmpty(mBookTitle)) {
            mBookTitle = SettingManager.getInstance().getBookTitle(mBookId, mCurChapterIndex);
        }
        String continueRead = getIntent().getStringExtra(EXTRA_CONTINUE_READ);
        if (!TextUtils.isEmpty(continueRead)) {
            mContinueRead = Boolean.parseBoolean(continueRead);
        }
        if (mContinueRead && mPageLoader != null) {
            // 根据上次的阅读记录去阅读
            mPageLoader.setChapterOpen(false);
        }
        mStartRead = false;
        if (flg) {
            // 读取章节内容
            readContentByNetOrLocal();
            // 获取书签信息
            if (mMarkAdapter != null) {
                updateMark();
            }
        }
        // 获取本书的简单章节信息
        ObtainAllSimpleChaptersHelper.getAllSimpleChaptersByForce(mBookId);
    }

    /**
     * 对极光vip特殊处理
     *
     * @param bean
     */
    protected void parseVipJpush(NotifyBean bean) {
        mIsJumpToHome = true;
        String bookId = mBookId;
        mBookId = bean.notify_book_id;
        if (!TextUtils.isEmpty(bean.notify_content_id)) {
            mCurChapterId = bean.notify_content_id;
        }
        if (!TextUtils.isEmpty(bean.notify_order_id)) {
            mCurChapterIndex = Integer.parseInt(bean.notify_order_id);
        }
        if (!TextUtils.isEmpty(bookId) && !TextUtils.equals(bookId, mBookId)) {
            resetBookId();
        }
    }

    /**
     * 重置bookid
     */
    private void resetBookId() {
        mStartRead = false;
        mCurChapterIndex = 0;
        super.processLogic();
        mPageLoader.resetBookId(mBookId);
    }

    @Override
    protected int getContentId() {
        return R.layout.activity_ad_new_reader_layout;
    }

    @Override
    protected ReadContract.Presenter bindPresenter() {
        return new ReadPresenter("1", mLifeCyclerSubject);
    }

    /**
     * 初始化翻页模式
     */
    private void initPageMode() {
        PageMode mPageMode = SettingManager.getInstance().getPageMode();
        switch (mPageMode) {
            case SIMULATION:
                mRbSimulation.setChecked(true);
                break;
            case COVER:
                mRbCover.setChecked(true);
                break;
            case SLIDE:
                mRbSlide.setChecked(true);
                break;
            case NONE:
                mRbNone.setChecked(true);
                break;
        }
    }

    /**
     * 初始化音量键开关展示
     */
    private void initVolume() {
        boolean volumeFlipEnable = SettingManager.getInstance().isVolumeFlipEnable();
        if (volumeFlipEnable) {
            mVolumeOpen.setChecked(true);
        } else {
            mVolumeClose.setChecked(true);
        }
        mVolumeSwitchContainer.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.volume_open:
                    SettingManager.getInstance().saveVolumeFlipEnable(true);
                    break;
                case R.id.volume_close:
                    SettingManager.getInstance().saveVolumeFlipEnable(false);
                    break;
            }
        });
    }

    /**
     * 初始化屏幕常亮参数
     */
    private void initScreenOnParams() {
        int param = SettingManager.getInstance().getScreenOnParam();
        switch (param) {
            case Constants.ScreenOnParams.SCREEN_ON_3_MIN:
                mScreenOn3Min.setChecked(true);
                break;
            case Constants.ScreenOnParams.SCREEN_ON_5_MIN:
                mScreenOn5Min.setChecked(true);
                break;
            case Constants.ScreenOnParams.SCREEN_ON_10_MIN:
                mScreenOn10Min.setChecked(true);
                break;
            case Constants.ScreenOnParams.SCREEN_ON_OFTEN:
                mScreenOnOften.setChecked(true);
                break;
        }
        // 屏幕常亮参数设置
        mScreenOnAlways.setOnCheckedChangeListener((group, checkedId) -> {
            int mins = Constants.ScreenOnParams.SCREEN_ON_OFTEN;
            switch (checkedId) {
                case R.id.min_3:
                    mins = Constants.ScreenOnParams.SCREEN_ON_3_MIN;
                    break;
                case R.id.min_5:
                    mins = Constants.ScreenOnParams.SCREEN_ON_5_MIN;
                    break;
                case R.id.min_10:
                    mins = Constants.ScreenOnParams.SCREEN_ON_10_MIN;
                    break;
                case R.id.min_ofen:
                    mins = Constants.ScreenOnParams.SCREEN_ON_OFTEN;
                    break;
                default:
                    break;
            }
            SettingManager.getInstance().setScreenOnParam(mins);
            mScreenOnHelper.setScreenOnMins(mins);
        });
    }

    /**
     * 初始化亮度
     */
    private void initBrightness() {
        // 亮度调整
        mSeekbarLightness.setMax(100);
        mSeekbarLightness.setOnSeekBarChangeListener(new SeekBarChangeListener());
        mSeekbarLightness.setProgress(SettingManager.getInstance().getReadBrightness());
        if (SettingManager.getInstance().isAutoBrightness()) {
            startAutoLightness();
        } else {
            stopAutoLightness();
        }
        mCbAutoBrightness.setOnCheckedChangeListener(new ChechBoxChangeListener());
        mCbAutoBrightness.setChecked(SettingManager.getInstance().isAutoBrightness());
        // 护眼模式
        mCbEyeShield.setChecked(SettingManager.getInstance().isEyeShieldMode());
        mCbEyeShield.setOnCheckedChangeListener(new ChechBoxChangeListener());
        mEyeShieldLayout.setVisibility(SettingManager.getInstance().isEyeShieldMode() ? View.VISIBLE : View.GONE);
        // 夜间模式
        toggleNightModeUI();
        mNightMode.setOnCheckedChangeListener(new ChechBoxChangeListener());
    }

    /**
     * 初始化阅读进度
     */
    private void initReadProgress() {
        mChapterSeekbar.setMax(100);
        mChapterSeekbar.setOnSeekBarChangeListener(new SeekBarChangeListener());
        BookRecordBean progress = SettingManager.getInstance().getCurReadProgress(mBookId);
        int count = SettingManager.getInstance().getChapterCount(mBookId);
        if (count > 0) {
            mChapterSeekbar.setProgress((progress.chapter * 100 / count));
        }
    }

    /**
     * 初始化主题
     */
    private void initTheme() {
        ThemeManager.setAdHeight(mAdHeight);
        mCurTheme = SettingManager.getInstance().getReadTheme();
        mReadThemes = ThemeManager.getReaderThemeData(mCurTheme);
        gvAdapter = new ReadThemeAdapter(this, R.layout.item_read_theme, (mReadThemes = ThemeManager.getReaderThemeData(mCurTheme)));
        mGvTheme.setAdapter(gvAdapter);
        gvAdapter.setSelected(mCurTheme);
    }

    /**
     * 处理硬件加速
     */
    private void handleLayerType() {
        // 如果 API < 18 取消硬件加速
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mPvPage.setLayerType(LAYER_TYPE_SOFTWARE, null);
        }
        if (RomUtils.isSmartisan()) {
            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        }
    }

    /**
     * 处理主题更换
     */
    private void handleThemeChange() {
        mGvTheme.setOnItemClickListener((adapterView, view, pos, l) -> {
            if (pos >= mReadThemes.size() || mPageLoader == null
                    || pos == gvAdapter.getSelected()) {
                return;
            }
            gvAdapter.setSelected(pos);
            // 说明是夜间主题色
            if (pos == 5) {
                isNightMode = true;
                mPageLoader.setNightMode(isNightMode);
            } else {
                mCurTheme = pos;
                if (isNightMode) {
                    mPageLoader.setNightMode(false);
                    toggleNightModeUI();
                }
                mPageLoader.setPageStyle(PageStyle.values()[pos]);
            }
            toggleNightModeUI();
            setAdBannerTheme();
        });
    }

    /**
     * 处理底部栏的点击事件
     */
    private void handleBottomMenuClick() {
        mLlBottomMenu.setTabChangeCallback(tabPos -> {
            switch (tabPos) {
                case BookReadBottomLayout.TAB_READER_PROGRESS:
                    if (isVisible(mLlBottomMenu)) {
                        if (isVisible(mReadProgressSet)) {
                            gone(mReadProgressSet);
                            animInOrOut(mReadProgressSet, false);
                            mLlBottomMenu.clearCheck();
                        } else {
                            gone(mRlReadAaSet, mReadBrightnessSet, mRlReadMark, mChapterProgressContainer);
                            calcReadProgress(mCurChapterIndex);
                            visible(mReadProgressSet);
                            animInOrOut(mReadProgressSet, true);
                        }
                    }
                    break;
                case BookReadBottomLayout.TAB_READER_BRIGHTNESS:
                    // 亮度设置
                    if (isVisible(mLlBottomMenu)) {
                        if (isVisible(mReadBrightnessSet)) {
                            gone(mReadBrightnessSet);
                            animInOrOut(mReadBrightnessSet, false);
                            mLlBottomMenu.clearCheck();
                        } else {
                            gone(mRlReadAaSet, mReadProgressSet, mRlReadMark);
                            visible(mReadBrightnessSet);
                            animInOrOut(mReadBrightnessSet, true);
                        }
                    }
                    break;
                case BookReadBottomLayout.TAB_READER_BOOKMARK:
                    // 书签
                    if (isVisible(mLlBottomMenu)) {
                        if (isVisible(mRlReadMark)) {
                            gone(mRlReadMark);
                            animInOrOut(mRlReadMark, false);
                            mLlBottomMenu.clearCheck();
                        } else {
                            gone(mRlReadAaSet, mReadProgressSet, mReadBrightnessSet);
                            updateMark();
                            visible(mRlReadMark);
                            animInOrOut(mRlReadMark, true);
                        }
                    }
                    break;
                case BookReadBottomLayout.TAB_READER_SETTINGS:
                    // 字体设置
                    if (isVisible(mLlBottomMenu)) {
                        if (isVisible(mRlReadAaSet)) {
                            gone(mRlReadAaSet);
                            animInOrOut(mRlReadAaSet, false);
                            mLlBottomMenu.clearCheck();
                        } else {
                            visible(mRlReadAaSet);
                            gone(mRlReadMark, mReadProgressSet, mReadBrightnessSet);
                            animInOrOut(mRlReadAaSet, true);
                        }
                    }
                    break;
            }
        });
    }

    /**
     * 处理拖动的进度
     */
    private void handleReadProgress(int progress) {
        // 处理之前先隐藏掉菜单栏
        gone(mAblTopMenu, mLlBottomMenu, mReadProgressSet);
        hideSystemBar();
        ObtainAllSimpleChaptersHelper.getAllSimpleChapters(mBookId, new INetCommCallback<List<SimpleChapterBean>>() {
            @Override
            public void onResponse(List<SimpleChapterBean> list) {
                if (Utils.isEmptyList(list) || mPageLoader == null) {
                    return;
                }
                int chapter = (progress * list.size()) / 100;
                chapter = chapter - 1;
                if (chapter >= list.size()) {
                    chapter = list.size() - 1;
                }
                if (chapter < 0) {
                    chapter = 0;
                }
                mCurChapterId = list.get(chapter).content_id;
                if (list.get(chapter).order.matches("[0-9]*")) {
                    mCurChapterIndex = Integer.valueOf(list.get(chapter).order);
                } else {
                    mCurChapterIndex = chapter + 1;
                }
                mStartRead = false;
                readCurrentChapter();
            }

            @Override
            public void onError(int code, String errDesc) {

            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        parseData();
        mScreenHeight = DisplayUtils.getScreenHeight(this) + MMKVDefaultManager.getInstance().getNotchHeight();
        mScreenWidth = DisplayUtils.getScreenWidth(this);
        mAdHeight = getResources().getDimensionPixelSize(R.dimen.px_150);
        mListPresenter = new BookListPresenter(null);
        // 屏幕常亮工具类
        mScreenOnHelper = new ScreenOnHelper(this);
        //获取阅读器视频播放辅助类并记录开始阅读时间
        mReaderAdHelper = new ReaderAdHelper(this);
        mReaderAdHelper.startReadTime();
        mAdTimerHelper.startTimer();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mScreenOnHelper.screenOn();
        if (mReaderAdHelper != null) {
            mReaderAdHelper.restartReadTime();
            mReaderAdHelper.mIsStop = false;
        }
        handleLayerType();
        isFetchBannerAd = true;
        if (mLastPageLabelLayout != null) {
            mLastPageLabelLayout.startShake();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 存储本地阅读记录
        mPageLoader.saveRecord();
        if (mLastPageLabelLayout != null) {
            mLastPageLabelLayout.stopShake();
        }
        //mScreenOnHelper.screenOff();
    }

    @Override
    protected void setUpToolbar(Toolbar toolbar) {
        super.setUpToolbar(toolbar);
        //设置标题
        //半透明化StatusBar
        SystemBarUtils.transparentStatusBar(this);
    }

    /**
     * 解析外部传入的参数
     */
    private void parseData() {
        // 支持scheme模式
        Uri uri = getIntent().getData();
        if (uri == null) {
            parseIntent();
            return;
        }
        if (uri.isOpaque()) {
            parseVipJpushChannel();
        } else {
            Set<String> names = uri.getQueryParameterNames();
            if (names != null && names.size() > 0) {
                for (String name : names) {
                    if (!TextUtils.isEmpty(name)) {
                        String val = uri.getQueryParameter(name);
                        getIntent().putExtra(name, val);
                    }
                }
            }
            parseIntent();
        }
        SettingManager.getInstance().saveReadBook(mBookId, true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 重置章节页面数量
        mSeekbarListenerPageCount = 0;
        setIntent(intent);
        // 处理阅读器菜单
        toggleReadBar(true);
        // 解析外部传入的参数
        parseData();
        // 开始阅读小说
        readCurrentChapter();
        if (mLastPageLabelLayout != null) {
            mRlBookReadRoot.removeView(mLastPageLabelLayout);
            mLastPageLabelLayout.destroy();
            mLastPageLabelLayout = null;
        }
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        // 硬件加速器适配
        handleLayerType();
        // 初始化阅读器引导页
        boolean entryReader = SettingManager.getInstance().isFirstEntryReader();
        // 获取到夜间模式状态
        isNightMode = SettingManager.getInstance().isNight();
        mReaderGuide.setVisibility(entryReader ? View.VISIBLE : View.GONE);
        //获取页面加载器
        mPageLoader = mPvPage.getPageLoader(mBookId);
        //设置字体显示结果
        mFontSizeResult.setText(String.valueOf(SettingManager.getInstance().getReadFontSize()));
        // 注册广播
        register();
        //隐藏StatusBar
        mPvPage.post(this::hideSystemBar);
        //初始化阅读进度
        initReadProgress();
        //初始化TopMenu
        initTopMenu();
        //初始化BottomMenu
        initBottomMenu();
        //初始化音量键显示
        initVolume();
        // 初始化主题
        initTheme();
        //亮度模块初始化
        initBrightness();
        // 初始化翻页模式
        initPageMode();
        // 初始化屏幕常亮参数
        initScreenOnParams();
    }

    private void observeScreenLightness() {
        mHandler = new SafeHandler(this);
        mLightnessObserver = new ContentObserver(mHandler) {
            @Override
            public void onChange(boolean selfChange) {
                if (SettingManager.getInstance().isAutoBrightness()) {
                    startAutoLightness();
                }
            }
        };
        getContentResolver().registerContentObserver(
                Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS), true, mLightnessObserver);
    }

    /**
     * 处理点击夜间和白天模式
     */
    private void processClickDayNight() {
        if (isNightMode) {
            mPageLoader.setNightMode(true);
            if (gvAdapter != null) {
                // 设置为选中
                gvAdapter.setSelected(5);
            }
        } else {
            mPageLoader.setNightMode(false);
            int pos = SettingManager.getInstance().getReadTheme();
            mPageLoader.setPageStyle(PageStyle.values()[pos]);
            if (gvAdapter != null) {
                gvAdapter.setSelected(mCurTheme);
            }
        }
        // 设置底部banner背景色
        setAdBannerTheme();
    }

    /**
     * 开始阅读
     */
    private void processRead() {
        if (TextUtils.isEmpty(mBookId)) {
            return;
        }
        // 开始阅读小说
        readCurrentChapter();
    }

    /**
     * 下载上一章和下一章的章节内容
     *
     * @param chapter
     */
    private void downLastAndNextContent(int chapter) {
        SimpleChapterBean info = SettingManager.getInstance().getSimpleChapterInfo(mBookId, chapter);
        // 如果存在文件才去缓存上一章和下一章数据
        if (info != null) {
            // 预加载上一章和下一章的数据
            // 获取当前章节内容id
            mCurChapterId = info.content_id;
            String next_content_id = info.next_content_id;
            if (!TextUtils.isEmpty(info.next_order)) {
                // 预先加载下一章
                int nextChapterIndex = Integer.parseInt(info.next_order);
                if (!TextUtils.isEmpty(next_content_id) && CacheManager.getInstance().getChapterFile(mBookId, nextChapterIndex) == null) {
                    getChapterContent(next_content_id, ChapterRequestParams.CACHED);
                }
            }
            // 预先加载上一章
            String last_content_id = info.last_content_id;
            if (!TextUtils.isEmpty(info.last_order) && !TextUtils.isEmpty(info.last_order)) {
                int lastChapterIndex = Integer.parseInt(info.last_order);
                if (!TextUtils.isEmpty(last_content_id) && lastChapterIndex > 0 && CacheManager.getInstance().getChapterFile(mBookId, lastChapterIndex) == null) {
                    getChapterContent(last_content_id, ChapterRequestParams.CACHED);
                }
            }
        } else {
            // 预下载 简单章节信息
            downloadSimpleChapter(chapter);
        }
    }

    /**
     * 读取章节内容从网络或者本地
     */
    private void readContentByNetOrLocal() {
        if (CacheManager.getInstance().getChapterFile(mBookId, mCurChapterIndex) != null) {
            // 从缓存中读取数据
            showChapterContent(null, mCurChapterIndex);
        } else {
            SimpleChapterBean info = SettingManager.getInstance().getSimpleChapterInfo(mBookId, mCurChapterIndex);
            if (info != null) {
                // 从网络获取
                mCurChapterId = info.content_id;
                initChapterContent();
            } else {
                downloadSimpleChapter(mCurChapterIndex, new INetCommCallback<SimpleChapterBean>() {
                    @Override
                    public void onResponse(SimpleChapterBean simpleChapterBean) {
                        if (simpleChapterBean == null) {
                            return;
                        }
                        mCurChapterId = simpleChapterBean.content_id;
                        initChapterContent();
                    }

                    @Override
                    public void onError(int code, String errDesc) {
                        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
                            mPageLoader.chapterError();
                            handleBookError(Constants.ErrCode.NetErr);
                        }
                    }
                });
            }
        }
    }

    /**
     * 开始读取当前章内容
     */
    private void readCurrentChapter() {
        // 从第几章开始读（外面参数传递了order信息过来）
        if (mCurChapterIndex >= 1) {
            // 重新修改pageloader中的章节序号
            if (mPageLoader != null) {
                mPageLoader.setCurChapterPos(mCurChapterIndex);
            }
        } else {
            // 默认mCurChapterIndex为空从pageLoader内部阅读器里面读取章节信息
            mCurChapterIndex = mPageLoader.getChapterPos();
            // 章节总数写入
            mPageLoader.setChapterCount(SettingManager.getInstance().getChapterCount(mBookId));
        }
        // 读取章节内容从网络或者本地
        readContentByNetOrLocal();
    }

    /**
     * 第一章的contentid为空
     * 根据章节id获取章节内容
     */
    private void initChapterContent() {
        getChapterContent(mCurChapterId, ChapterRequestParams.UN_CACHED);
    }

    /**
     * 读取章节内容，如果为0则是正常读，1则是用于缓存数据
     *
     * @param content_id
     * @param is_cache
     */
    private void getChapterContent(String content_id, int is_cache) {
        ChapterRequestParams params = new ChapterRequestParams();
        params.book_id = mBookId;
        params.content_id = content_id;
        params.is_cache = is_cache;
        // 下一个章节的内容
        mPresenter.getChapterContent(params,0);
    }

    /**
     * 显示章节内容
     * 如果是当前章，此时会进入阅读器
     *
     * @param content
     * @param chapterIndex
     */
    private void showChapterContent(String content, int chapterIndex) {
        // 先缓存内容
        if (!TextUtils.isEmpty(content)) {
            CacheManager.getInstance().saveChapterFile(mBookId, chapterIndex, content);
        }
        // 第一次会调用以下代码
        File chapterFile = CacheManager.getInstance().getChapterFile(mBookId, chapterIndex);
        if (!mStartRead && chapterFile != null) {
            // 隐藏错误页面
            DisplayUtils.gone(mErrorLayout);
            // 隐藏摇一摇页面
            DisplayUtils.gone(mLastPageLabelLayout);
            mStartRead = true;
            // 設置章節總數
            mPageLoader.setChapterCount(SettingManager.getInstance().getChapterCount(mBookId));
            mCurChapterIndex = chapterIndex;
            // 跳轉到指定章節 进入pageloader逻辑
            mPageLoader.skipToChapter(chapterIndex);
        }
    }

    /**
     * 初始化顶部栏
     */
    private void initTopMenu() {
        if (Build.VERSION.SDK_INT >= 19) {
            mAblTopMenu.setPadding(0, DisplayUtils.getStatusBarHeight(this), 0, 0);
        }
    }

    /**
     * 初始化底部栏
     */
    private void initBottomMenu() {
        //设置mBottomMenu的底部距离
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mLlBottomMenu.getLayoutParams();
        params.bottomMargin = 0;
        mLlBottomMenu.setLayoutParams(params);
        // 显示导航栏
        SystemBarUtils.showStableNavBar(this);
        // 处理底部栏的点击事件
        handleBottomMenuClick();
    }

    /**
     * 下载简单章节信息
     *
     * @param chapter
     */
    private void downloadSimpleChapter(int chapter) {
        downloadSimpleChapter(chapter, null);
    }

    /**
     * 下载简单章节内容信息
     *
     * @param chapter
     * @param callback
     */
    private void downloadSimpleChapter(int chapter, final INetCommCallback<SimpleChapterBean> callback) {
        mPresenter.getSimpleChapterInfo(mBookId, chapter + "", new INetCommCallback<SimpleChapterBean>() {
            @Override
            public void onResponse(SimpleChapterBean simpleChapterBean) {
                SettingManager.getInstance().saveSimpleChapterInfo(mBookId, chapter, simpleChapterBean);
                if (callback != null) {
                    callback.onResponse(simpleChapterBean);
                }
            }

            @Override
            public void onError(int code, String errDesc) {
                Log.d("wcy", "getSimpleChapterInfoByMMKV---");
                if (callback != null) {
                    callback.onError(code, errDesc);
                }
            }
        });
    }

    /**
     * 下载某一个章节内容
     *
     * @param chapter
     */
    private void downChapter(int chapter) {
        if (CacheManager.getInstance().getChapterFile(mBookId, chapter) != null) {
            return;
        }
        SimpleChapterBean info = SettingManager.getInstance().getSimpleChapterInfo(mBookId, chapter);
        if (info != null) {
            getChapterContent(info.content_id, ChapterRequestParams.UN_CACHED);
            return;
        } else {
            downloadSimpleChapter(chapter, new INetCommCallback<SimpleChapterBean>() {
                @Override
                public void onResponse(SimpleChapterBean simpleChapterBean) {
                    getChapterContent(simpleChapterBean.content_id, ChapterRequestParams.UN_CACHED);
                }

                @Override
                public void onError(int code, String errDesc) {

                }
            });
        }
    }

    /**
     * 处理夜间和白天的UI
     */
    private void toggleNightModeUI() {
        // 从本地文件中取值
        isNightMode = SettingManager.getInstance().isNight();
        // 设置夜间模式UI
        mNightMode.setChecked(isNightMode);
        if (isNightMode) {
            if (gvAdapter != null) {
                // 设置为选中
                gvAdapter.setSelected(5);
            }
        }
    }

    /**
     * 处理pageloader数据改变
     */
    private void handlePageChange() {
        mPageLoader.setOnPageChangeListener(
                new PageLoader.OnPageChangeListener() {
                    private BookRecordBean mRecordBean = new BookRecordBean();

                    @Override
                    public void onChapterChange(int pos) {
                        mSeekbarListenerPageCount = 0;
                        Log.d("尾页", "onChapterChange" + mSeekbarListenerPageCount);
                        // 上一个章节只有一页，阅读完毕调用 发送阅读时间到后台
                        if (!TextUtils.equals(mCurrentChapterPos, mCurChapterId)) { // 切换章节 保存上一个章节信息
                            uploadReadTime(false);
                            // 切换章节  则重新计时
                            mCurrentChapterPos = mCurChapterId;
                            mOldTime = System.currentTimeMillis();
                        }
                        // 预加载上一章和下一章的数据
                        downLastAndNextContent(pos);
                        // 告诉后台阅读记录
                        notifyServerReadedChapter();
                        if (mCurChapterIndex != pos) {
                            // 当前章节序号重新设置
                            mCurChapterIndex = pos;
                            // 获取广告(底部banner和章节衔接广告)
                            acquireAd();
                        } else if (!mIsFirstRender) {
                            // 当前章节序号重新设置
                            mCurChapterIndex = pos;
                            acquireAd();
                            mIsFirstRender = true;
                        }
                    }

                    @Override
                    public void requestChapters(List<TxtChapter> requestChapters) {
                        Log.d("PageChangeListener", "requestChapters");
                        //隐藏提示
                        for (int i = 0; i < requestChapters.size(); i++) {
                            downChapter(requestChapters.get(i).chapterIndex);
                        }
                    }

                    @Override
                    public void requestChapter(final int chapter) {
                        Log.d("PageChangeListener", "requestChapter");
                        // 获取简单章节信息
                        SimpleChapterBean info = SettingManager.getInstance().getSimpleChapterInfo(mBookId, chapter);
                        if (info == null) {
                            downloadSimpleChapter(chapter, new INetCommCallback<SimpleChapterBean>() {
                                @Override
                                public void onResponse(SimpleChapterBean simpleChapterBean) {
                                    // 获取content_id
                                    mCurChapterId = simpleChapterBean.content_id;
                                    Log.d("wcy", "requestChapter pos:" + chapter + "content_id" + mCurChapterId);
                                    // 改变标记位重新去刷新
                                    mStartRead = false;
                                    mCurChapterIndex = chapter;
                                    readContentByNetOrLocal();
                                }

                                @Override
                                public void onError(int code, String errDesc) {
                                    if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
                                        mPageLoader.chapterError();
                                        handleBookError(Constants.ErrCode.NetErr);
                                    }
                                }
                            });
                            return;
                        }
                        // 获取content_id
                        mCurChapterId = info.content_id;
                        Log.d("PageChangeListener", "requestChapter pos:" + chapter + "content_id" + mCurChapterId);
                        // 改变标记位重新去刷新
                        mStartRead = false;
                        mCurChapterIndex = chapter;
                        readContentByNetOrLocal();
                    }

                    @Override
                    public void onPageCountChange(int count) {
                        mCurrentChapterCount = count;
                        mSeekbarListenerPageCount = count;
                        Log.d("PageChangeListener", "onPageCountChange ： pagecount " + count);
                    }

                    @Override
                    public void onPageChange(int pos) {
                        mSeekbarListenerPageCount = mCurrentChapterCount;
                        // 最后一页 上传阅读记录
                        if (mCurrentChapterCount > 1 && pos == mCurrentChapterCount - 1 && mOldTime != 0) {
                            uploadReadTime(true);
                        }
                        Log.d("PageChangeListener", "onPageChange ： pos " + pos);
                        // 统计阅读页数
                        ARouter.getInstance().navigation(IMakeMoneyService.class).saveStatisticsInfo();
                        // 保存一下本地阅读记录
                        mRecordBean.setBookId(mBookId);
                        mRecordBean.setChapter(mCurChapterIndex);
                        mRecordBean.setItemPos(pos);
                        SettingManager.getInstance().saveReadProgress(mRecordBean);
                    }

                    @Override
                    public void onNoPrev() {
                        if (mPageLoader.getChapterPos() == 1) {
                            ToastUtil.showMessage("没有上一页啦");
                        }
                    }

                    @Override
                    public void onNoNext() {
                        //ToastUtil.showMessage("没有下一页啦");
                        if (mLastPageLabelLayout == null && mCurChapterIndex != 0 && mPageLoader.getChapterCount() != 0 && mSeekbarListenerPageCount != 0) {
                            mLastPageLabelLayout = new LastPageLabelLayout(AdBookReaderActivity.this, mBookId);
                            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                            mLastPageLabelLayout.setLayoutParams(params);
                            mRlBookReadRoot.addView(mLastPageLabelLayout);
                        }
                    }
                }
        );

        mPvPage.setTouchListener(new PageView.TouchListener() {
            @Override
            public boolean onTouch() {
                return !hideReadMenu();
            }

            @Override
            public void center() {
                toggleReadBar(true);
            }

            @Override
            public void prePage() {
            }

            @Override
            public void nextPage() {
            }

            @Override
            public void cancel() {
            }
        });
    }

    /**
     * 上传阅读章节时间
     *
     * @param isEnd 是否是章节尾页
     */
    private void uploadReadTime(boolean isEnd) {
        if (mOldTime != 0 && !TextUtils.isEmpty(mCurrentChapterPos)) {
            long consuming = System.currentTimeMillis() - mOldTime;
            if (consuming > -1 && consuming < 1000) {
                return;
            }
            if (isEnd) {
                consuming += (consuming / (mCurrentChapterCount - 1)) / 2; // 最后一页阅读时间加前面的平均值
            }
            Log.d("upLoadUserReadaction", "consuming: " + consuming);
            if (consuming < 0) {
                consuming = 20 * 60 * 1000;
            } else if (consuming < 2000) { // 最低2秒钟
                consuming = 2 * 1000;
            }
            mPresenter.upLoadUserReadaction(mBookId, mCurrentChapterPos, mCurrentChapterCount, consuming);
            if (isEnd) {
                mOldTime = 0;
            }
        }
    }

    /**
     * 处理翻页模式改变
     */
    private void handlePageModeChange() {
        mRgPageMode.setOnCheckedChangeListener(
                (group, checkedId) -> {
                    PageMode pageMode;
                    switch (checkedId) {
                        case R.id.read_setting_rb_simulation:
                            pageMode = SIMULATION;
                            break;
                        case R.id.read_setting_rb_cover:
                            pageMode = COVER;
                            break;
                        case R.id.read_setting_rb_slide:
                            pageMode = SLIDE;
                            break;
                        case R.id.read_setting_rb_none:
                            pageMode = SCROLL;
                            break;
                        default:
                            pageMode = SIMULATION;
                            break;
                    }
                    mPageLoader.setPageMode(pageMode);
                }
        );
    }

    @Override
    protected void initClick() {
        super.initClick();
        // 处理主题更换
        handleThemeChange();
        // 处理pageloader数据改变
        handlePageChange();
        //Page Mode 切换 翻页模式
        handlePageModeChange();
    }

    /**
     * 隐藏阅读界面的菜单显示
     *
     * @return 是否隐藏成功
     */
    private boolean hideReadMenu() {
        mLlBottomMenu.clearCheck();
        if (isVisible(mReadProgressSet)) {
            gone(mReadProgressSet);
            animInOrOut(mReadProgressSet, false);
            return true;
        }
        if (isVisible(mReadBrightnessSet)) {
            gone(mReadBrightnessSet);
            animInOrOut(mReadBrightnessSet, false);
            return true;
        }
        if (isVisible(mRlReadAaSet)) {
            gone(mRlReadAaSet);
            animInOrOut(mRlReadAaSet, false);
            return true;
        }
        if (isVisible(mRlReadMark)) {
            gone(mRlReadMark);
            animInOrOut(mRlReadMark, false);
            return true;
        }
        hideSystemBar();
        if (isVisible(mAblTopMenu)) {
            toggleReadBar(true);
            return true;
        }
        return false;
    }


    private void showSystemBar() {
        //如果是刘海屏，则不做处理
        if (QMUINotchHelper.hasNotch(this)) {
            if (QMUINotchHelper.isNotchOfficialSupport()) {
                DisplayUtils.setTranslucent(this);
                SystemBarUtils.showUnStableStatusBar(this);
            } else {
                SystemBarUtils.hideStableStatusBar(this);
                return;
            }
        } else {
            SystemBarUtils.showUnStableStatusBar(this);
            quitFullScreen();
        }
    }

    private void hideSystemBar() {
        if (QMUINotchHelper.hasNotch(this)) {
            if (QMUINotchHelper.isNotchOfficialSupport()) {
                quitFullScreen();
                DisplayUtils.setTranslucent(this);
            }
        } else {
            //如果不是刘海屏,隐藏
            SystemBarUtils.hideStableStatusBar(this);
            setFullScreen();
        }
        if (mLlBottomMenu != null)
            mLlBottomMenu.clearCheck();
    }

    private void setFullScreen() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void quitFullScreen() {
        final WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setAttributes(attrs);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }


    @Override
    protected void processLogic() {
        super.processLogic();
        // 改变书籍状态(更新标记)
        AndroidSchedulers.mainThread().scheduleDirect(() -> {
            ShelfEvent event = new ShelfEvent(ShelfEvent.UPDATE_BOOK_STATUS);
            event.obj = mBookId;
            EventBus.getDefault().post(event);
        }, 1200, TimeUnit.MILLISECONDS);
        // 定时上报逻辑打开
        ARouter.getInstance().navigation(IMakeMoneyService.class).activateStatisticsService();
        // 开始阅读小说
        processRead();
    }

    /**
     * 显示章节内容
     *
     * @param chapterBean
     */
    @Override
    public void showContent(BaseResult<ChapterBean> chapterBean, int loadType) {
        if (BaseResult.isNotNull(chapterBean) && chapterBean.result.status != null) {
            int code = chapterBean.result.status.code;
            ChapterBean data = chapterBean.result.data;
            if (data == null) {
                if (!TextUtils.isEmpty(chapterBean.result.status.msg)) {
                    ToastUtil.showMessage(chapterBean.result.status.msg);
                }
                if (code == Constants.ErrCode.Offline) {
                    // 下线标记
                    if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
                        mPageLoader.bookOffline();
                        handleBookError(code);
                    }
                    return;
                }
                // 显示加载失败
                if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
                    mPageLoader.chapterError();
                    handleBookError(Constants.ErrCode.NetErr);
                }
                return;
            }
            if (TextUtils.isEmpty(data.order)) {
                return;
            }
            int pageIndex = Integer.parseInt(data.order);
            Log.d("http", "pageIndex:(parse)" + pageIndex);
            if (data.book_info != null) {
                mBookTitle = data.book_info.book_title;
                mPageLoader.setBookTitle(mBookTitle);
                // 存储当前书籍信息
                if (!mStartRead) {
                    DiskLruCacheUtils.put(mBookId + "simple", data.book_info, true);
                }
                // 从后台知道当前书籍是否收藏过
                mJoinShelfFromServer = TextUtils.equals("1", chapterBean.result.data.book_info.join_bookcase);
                //保存书籍分类和连载
                MMKVDefaultManager.getInstance().setBookAttribute(data.book_info.book_id, data.book_info.writing_process, data.book_info.category_id_1);
            }
            // 获取数据成功
            int count = Integer.parseInt(TextUtils.isEmpty(data.book_info.chapter_count) ? "1" : data.book_info.chapter_count);
            // 保存章节总数
            mPageLoader.setChapterCount(count);
            // 保存扉页信息
            if (pageIndex == 1) {
                mPageLoader.setHeadpageInfo(data.cp_info);
            }
            // 做一定的调整(有可能后台给出错误的数据)
            if (pageIndex > mPageLoader.getChapterCount()) {
                pageIndex = mPageLoader.getChapterCount();
            }
            // 保存当前章节的简单信息
            SettingManager.getInstance().saveSimpleChapterInfo(mBookId, pageIndex, data);
            if (code == Constants.ErrCode.SUCCESS) {
                // 显示内容
                if (!TextUtils.isEmpty(data.content)) {
                    if (pageIndex == mCurChapterIndex) {
                        if (mPageLoader != null) {
                            mPageLoader.setCurChapterTitle(data.title);
                        }
                    }
                    showChapterContent(data.content, pageIndex);
                } else {
                    // 显示数据为空
                    if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
                        mPageLoader.chapterEmpty();
                    }
                }
            } else if (code == Constants.ErrCode.InsufficientBalance
                    || code == Constants.ErrCode.BuyToRead
                    || code == Constants.ErrCode.FailToConsumeByBalance) {
                if (pageIndex != mCurChapterIndex) {
                    Log.d("http", "pageIndex:" + pageIndex + ",mCurChapterIndex" + mCurChapterIndex);
                    ToastUtil.showMessage("余额不足");
                    return;
                }
                // 下载简单章节信息
                downloadSimpleChapter(pageIndex);
            } else {
                ToastUtil.showMessage(chapterBean.result.status.msg);
            }
        }
    }

    @Override
    public void showError(String contentId, int code, String desc) {
        // 获取数据失败 处理各种状态码
        //ToastUtil.showMessage(getString(R.string.standard_net_tip));
        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING
                && TextUtils.equals(contentId, mCurChapterId)) {
            mPageLoader.chapterError();
            handleBookError(Constants.ErrCode.NetErr);
        }
    }

    /**
     * 充值完成
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlePayActionEvent(PayActionEvent event) {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleShelfEvent(ShelfEvent event) {
        switch (event.code) {
            case ShelfEvent.ADD_TO_SHELF_SUCCESS:
                ToastUtil.showMessage("加入书架成功");
                break;
            default:
                break;
        }
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        mLlBottomMenu.clearCheck();
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (isVisible(mRlReadAaSet)) {
                    gone(mRlReadAaSet);
                    animInOrOut(mRlReadAaSet, false);
                    return true;
                } else if (isVisible(mRlReadMark)) {
                    gone(mRlReadMark);
                    animInOrOut(mRlReadMark, false);
                    return true;
                } else if (isVisible(mReadProgressSet)) {
                    gone(mReadProgressSet);
                    animInOrOut(mReadProgressSet, false);
                    return true;
                } else if (isVisible(mReadBrightnessSet)) {
                    gone(mReadBrightnessSet);
                    animInOrOut(mReadBrightnessSet, false);
                    return true;
                } else if (isVisible(mAblTopMenu)) {
                    hideSystemBar();
                    boolean isVisibleBottom = isVisible(mLlBottomMenu);
                    // 顶部菜单栏
                    gone(mAblTopMenu, mLlBottomMenu);
                    if (isVisibleBottom) {
                        Animation animation = AnimationUtils.loadAnimation(mLlBottomMenu.getContext(), R.anim.push_bottom_out);
                        mLlBottomMenu.startAnimation(animation);
                    }
                    Animation animation1 = AnimationUtils.loadAnimation(mLlBottomMenu.getContext(), R.anim.push_top_out);
                    mAblTopMenu.startAnimation(animation1);
                    return true;
                } else {
                    // 处理加入书架
                    int code = processJoinShelf();
                    if (code == 0) {
                        // 看看是不是要跳转到主页面
                        Utils.jumpToHomeIfNeed();
                        return super.onKeyUp(keyCode, event);
                    }
                    return true;
                }
            case KeyEvent.KEYCODE_MENU:
                toggleReadBar(true);
                return true;
            default:
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onAdLoadSucceeded(@Nullable View view) {
        refreshPage();
    }

    @Override
    public void onAdLoadFailed() {
        closeAdBanner();
    }

    @Override
    public void onAdClicked() {
    }

    @Override
    public void onADClosed() {
        closeAdBanner();
    }


    @Override
    public void onBackAd(@NotNull Object ad) {
        //返回banner广告对象来判断在阅读器中是否限制高度
        if (ad instanceof CenBanner) {
            mAdHeight = (int) (mScreenWidth / (640 / 100f));
        }
    }

    /**
     * 刷新页面
     */
    private void refreshPage() {
        if (mWrapAdContainer == null) {
            return;
        }
        mLoadSuccShowAd = true;
        DisplayUtils.visible(mWrapAdContainer);
        setAdBannerTheme();
        ThemeManager.setAdHeight(mAdHeight);
        int tmpMode = mAdHeight > getResources().getDimensionPixelSize(R.dimen.px_150) ? MODE_AD_HEIGHT_HIGH : MODE_AD_HEIGHT_DEFAULT;
        // 广告显示高度  模式 发生改变 需要刷新页面
        if (mCurrentAdHeightMode != tmpMode) {
            ViewGroup.LayoutParams params = mWrapAdContainer.getLayoutParams();
            if (mAdHeight > getResources().getDimensionPixelSize(R.dimen.px_150)) {
                params.height = mAdHeight > getResources().getDimensionPixelSize(R.dimen.px_200) ? getResources().getDimensionPixelSize(R.dimen.px_200) : mAdHeight;
                mCurrentAdHeightMode = MODE_AD_HEIGHT_HIGH;
            } else {
                params.height = getResources().getDimensionPixelSize(R.dimen.px_150);
                mCurrentAdHeightMode = MODE_AD_HEIGHT_DEFAULT;
            }
            mWrapAdContainer.setLayoutParams(params);
            // 重新设置阅读器高度
            mPageLoader.setVisibleHeight(mScreenHeight - mAdHeight);
            // 刷新阅读器
            int fontSizePx = SettingManager.getInstance().getReadFontSize();
            mPageLoader.setTextSize(fontSizePx);
        }
    }

    private static class SafeHandler extends Handler {
        private WeakReference<Context> reference;

        public SafeHandler(Context context) {
            reference = new WeakReference<>(context);
        }

    }

    @Override
    protected void onStop() {
        if (mReaderAdHelper != null) {
            mReaderAdHelper.mIsStop = true;
            mReaderAdHelper.countReadTime();
        }
        isFetchBannerAd = false;
        if (mLastPageLabelLayout != null) {
            mLastPageLabelLayout.stopShake();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        uploadReadTime(false);
        mPageLoader.closeBook();
        if (mReaderAdHelper != null) {
            mReaderAdHelper.destroyAd();
            mReaderAdHelper = null;
        }
        RxTimerUtils.cancel();
        mLifeCyclerSubject.onNext(ACTION_DESTORY);
        mHandler.removeCallbacksAndMessages(null);
        mScreenOnHelper.clear();
        mListPresenter.detachView();
        unregister();
        // 发送页面退出广播
        EventBus.getDefault().post(new ReaderFinishEvent());
        Utils.fixInputMethodManagerLeak(this);
        Utils.fixHwChangeWindowCtrlLeak();
        AdUtils.destroyAd(mAdContainer);
        if (mAdTimerHelper != null) {
            mAdTimerHelper.stopTimer();
        }
        if (mLastPageLabelLayout != null) {
            mLastPageLabelLayout.destroy();
        }
        // 刷新书架数据
        refreshShelfData();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (SettingManager.getInstance().isVolumeFlipEnable()) {
                    if (mAdBetweenChaptersLayout != null && mAdBetweenChaptersLayout.getVisibility() == View.VISIBLE) {
                        mAdBetweenChaptersLayout.setVisibility(View.GONE);
                        return true;
                    }
                    hideReadBar();
                    hideReadBar();
                    hideSystemBar();
                    if (mPageLoader != null) {
                        mPageLoader.skipToNextPage();
                    }
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (SettingManager.getInstance().isVolumeFlipEnable()) {
                    if (mAdBetweenChaptersLayout != null && mAdBetweenChaptersLayout.getVisibility() == View.VISIBLE) {
                        mAdBetweenChaptersLayout.setVisibility(View.GONE);
                        return true;
                    }
                    hideReadBar();
                    hideReadBar();
                    hideSystemBar();
                    if (mPageLoader != null) {
                        mPageLoader.skipToPrePage();
                    }
                    return true;
                }
                break;

        }
        return super.onKeyDown(keyCode, event);
    }

    private static void animInOrOut(View view, boolean inOrOut) {
        if (RomUtils.isSmartisan()) {
            return;
        }
        Animation animation = AnimationUtils.loadAnimation(view.getContext(), inOrOut ? R.anim.tran_next_in : R.anim.tran_next_out);
        view.startAnimation(animation);
    }

    /**
     * 更新书签
     */
    private void updateMark() {
        if (mMarkAdapter == null) {
            mMarkAdapter = new BookmarkAdapter(this, R.layout.item_read_mark, mMarkList);
            mLvMark.setAdapter(mMarkAdapter);
            mLvMark.setOnItemClickListener((parent, view, position, id) -> {
                BookMark mark = mMarkList.get(position);
                if (mark != null) {
                    mark.textSize = mark.textSize == 0 ? SettingManager.getInstance().getReadFontSize() : mark.textSize;
                    if (mark.position == 0 && mark.startPos > 0) {
                        // 兼容之前老阅读器的数据
                        mark.position = mark.startPos / 1000;
                    }
                    if (mPageLoader != null) {
                        // 隐藏章节之间的广告
                        DisplayUtils.gone(mAdBetweenChaptersLayout);
                        mPageLoader.skipToMark(mark.chapter, mark.position, mark.textSize);
                        // 兼容之前的老版本阅读器数据
                        if (mark.startPos > 0) {
                            // 移除之前的老的数据，用新的代替
                            SettingManager.getInstance().removeBookMarkForOldReader(mBookId, mark);
                            addBookMark(false);
                        }
                    }
                    mLlBottomMenu.clearCheck();
                    hideSystemBar();
                    gone(mRlReadAaSet, mRlReadMark, mLlBottomMenu, mAblTopMenu);
                } else {
                    ToastUtil.showMessage("书签无效");
                }
            });
        }
        if (mMarkList != null) {
            mMarkList.clear();
        }
        mMarkList = SettingManager.getInstance().getBookMarks(mBookId);
        if (mMarkList != null && mMarkList.size() > 0) {
            Collections.reverse(mMarkList);
        }
        mMarkAdapter.setData(mMarkList);
    }

    /**
     * 添加书签
     */
    public void addBookMark(boolean showToast) {
        if (mPageLoader == null) {
            return;
        }
        int pageStatus = mPageLoader.getPageStatus();
        if (pageStatus != PageLoader.STATUS_FINISH) {
            ToastUtil.showMessage("章节内容没有加载完成，不能添加书签");
            return;
        }
        BookMark mark = new BookMark();
        mark.chapter = mPageLoader.getChapterPos();
        mark.position = mPageLoader.getPagePos();
        mark.textSize = SettingManager.getInstance().getReadFontSize();
        if (mark.chapter >= 1 && mark.chapter <= SettingManager.getInstance().getChapterCount(mBookId)) {
            mark.title = mPageLoader.getCurChapterTitle();
            if (TextUtils.isEmpty(mark.title)) {
                mark.title = SettingManager.getInstance().getCurBookChapterTitle(mBookId, mark.chapter);
            }
        }
        mark.desc = mPageLoader.getHeadLine();
        if (SettingManager.getInstance().addBookMark(mBookId, mark)) {
            if (showToast) {
                ToastUtil.showMessage("添加书签成功");
            }
            updateMark();
        } else {
            if (showToast) {
                ToastUtil.showMessage("书签已存在");
            }
        }
    }


    @OnClick({R.id.tvFontsizeMinus, R.id.tvFontsizePlus, R.id.tvClear,
            R.id.tvAddMark, R.id.ivBack, R.id.reader_guide, R.id.share,
            R.id.chapter_list_entry, R.id.more_entry, R.id.pre_chapter,
            R.id.next_chapter, R.id.brightness_minus, R.id.brightness_plus,
            R.id.download})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvFontsizeMinus:
                // 字体大小减少
                String s = mFontSizeResult.getText().toString().trim();
                int progress = Integer.parseInt(s);
                calcFontSize(progress - 1);
                break;
            case R.id.tvFontsizePlus:
                // 字体大小增加
                String s1 = mFontSizeResult.getText().toString().trim();
                int progress1 = Integer.parseInt(s1);
                calcFontSize(progress1 + 1);
                break;
            case R.id.tvClear:
                // 书签清除
                SettingManager.getInstance().clearBookMarks(mBookId);
                updateMark();
                break;
            case R.id.tvAddMark:
                // 添加书签
                addBookMark(true);
                break;
            case R.id.ivBack:
                gone(mRlReadAaSet);
                //animInOrOut(mRlReadAaSet, true);
                hideReadBar();
                if (mIsJumpToHome) {
                    ARouterUtils.toActivity(ARouterConfig.HOME_PAGE);
                    finish();
                    return;
                }
                int flg = processJoinShelf();
                if (flg == 0) {
                    finish();
                }
                break;
            case R.id.reader_guide:
                gone(mReaderGuide);
                SettingManager.getInstance().saveFirstEntryReader(false);
                break;
            case R.id.download:
                if (!MMKVUserManager.getInstance().isUserLogin()) {
                    ARouterUtils.toActivity(ARouterConfig.PERSONAL_LOGIN_IN, "phone", "");
                } else {
                    ARouterUtils.toActivity(ARouterConfig.DOWNLOAD_DOWNLOAD_CHAPTER, "book_id", mBookId);
                }
                break;
            case R.id.share:
                DisplayUtils.gone(mLlBottomMenu, mReadBrightnessSet, mReadProgressSet, mRlReadMark, mRlReadAaSet);
                ReaderShareDialog.show(this, mBookId, mCurChapterId);
                break;
            case R.id.chapter_list_entry:
                Map<String, String> map = new HashMap<>();
                map.put("book_id", mBookId);
                map.put("book_chapter", mCurChapterIndex + "");
                ARouterUtils.toActivity(ARouterConfig.BOOK_CHAPTER_LIST, map);
                break;
            case R.id.more_entry:
                ReaderPopupWindowHelper.showPopupWindow(this, mMoreEntry, mToolbar, mBookId);
                break;
            case R.id.pre_chapter:
                // 先隐藏掉之间衔接广告
                DisplayUtils.gone(mAdBetweenChaptersLayout);
                preChapter();
                calcReadProgress(mCurChapterIndex);
                break;
            case R.id.next_chapter:
                // 先隐藏掉之间衔接广告
                DisplayUtils.gone(mAdBetweenChaptersLayout);
                nextChapter();
                calcReadProgress(mCurChapterIndex);
                break;
            case R.id.brightness_minus:
                SettingManager.getInstance().saveReadBrightness(mSeekbarLightness.getProgress() - 1);
                stopAutoLightness();
                break;
            case R.id.brightness_plus:
                SettingManager.getInstance().saveReadBrightness(mSeekbarLightness.getProgress() + 1);
                stopAutoLightness();
                break;
            default:
                break;
        }
    }

    @Override
    public void finish() {
        Utils.jumpToHomeIfNeed();
        super.finish();
    }

    /**
     * 计算字体大小
     *
     * @param progress
     */
    private void calcFontSize(int progress) {
        int dpValue = DisplayUtils.px2dip(this, progress);
        if (dpValue < 12 || dpValue > 36) {
            return;
        }
        mFontSizeResult.setText(String.valueOf(progress));
        mPageLoader.setTextSize(progress);
    }

    /**
     * 计算章节阅读进度
     *
     * @param chapterIndex
     */
    private void calcReadProgress(int chapterIndex) {
        int chapterCount = mPageLoader.getChapterCount();
        if (chapterCount > 0) {
            mChapterSeekbar.setProgress((chapterIndex * 100 / chapterCount));
        }
    }

    /**
     * 处理是否添加到书架
     *
     * @return 0 已经加入书架 1没有加入书架
     */
    private int processJoinShelf() {
        // 刷新最近阅读信息
        ShelfEvent event = new ShelfEvent(ShelfEvent.REFRESH_RECENT);
        event.obj = mBookId;
        EventBus.getDefault().post(event);
        boolean flg = false;
        List<BookInfo> bookInfos = SettingManager.getInstance().getShelfInfos();
        if (Utils.isEmptyList(bookInfos)) {
            bookInfos = SettingManager.getInstance().getShelfInfosFromSd();
        }
        if (!Utils.isEmptyList(bookInfos)) {
            for (BookInfo bookInfo : bookInfos) {
                if (TextUtils.equals(mBookId, bookInfo.book_id)) {
                    flg = true;
                    break;
                }
            }
        }
        if (flg || mJoinShelfFromServer) {
            return 0;
        }
        CustomDialog.show(this, "加入收藏", "是否将本书加入我的收藏", new CustomDialog.Callback() {
            @Override
            public void onSure(Dialog dialog) {
                if (dialog == null) {
                    return;
                }
                dialog.dismiss();
                BookPresenter bookPresenter = new BookPresenter(null);
                bookPresenter.joinBookShelf(mBookId);
                finish();
            }

            @Override
            public void onCancel(Dialog dialog) {
                if (dialog != null && !isFinishing()) {
                    dialog.dismiss();
                    finish();
                }
            }
        }, false, "下次再说", "加入收藏");
        return 1;
    }

    private synchronized void hideReadBar() {
        hideReadBar(false);
    }

    public synchronized void hideReadBar(boolean hideSystembar) {
        mLlBottomMenu.clearCheck();
        if (isVisible(mRlReadAaSet)) {
            gone(mRlReadAaSet);
            animInOrOut(mRlReadAaSet, false);
            return;
        }
        if (isVisible(mRlReadMark)) {
            gone(mRlReadMark);
            animInOrOut(mRlReadMark, false);
            return;
        }
        if (isVisible(mReadBrightnessSet)) {
            gone(mReadBrightnessSet);
            animInOrOut(mReadBrightnessSet, false);
            return;
        }
        if (isVisible(mReadProgressSet)) {
            gone(mReadProgressSet);
            animInOrOut(mReadProgressSet, false);
            gone(mChapterProgressContainer);
            return;
        }
        if (hideSystembar) {
            hideSystemBar();
        }
        if (isGone(mAblTopMenu)) {
            return;
        }
        boolean isVisibleBottom = isVisible(mLlBottomMenu);
        gone(mRlReadAaSet, mRlReadMark, mLlBottomMenu, mAblTopMenu);
        if (isVisibleBottom) {
            Animation animation = AnimationUtils.loadAnimation(mLlBottomMenu.getContext(), R.anim.push_bottom_out);
            mLlBottomMenu.startAnimation(animation);
        }
        Animation animation1 = AnimationUtils.loadAnimation(mLlBottomMenu.getContext(), R.anim.push_top_out);
        mAblTopMenu.startAnimation(animation1);
        // 清除选中状态
        mLlBottomMenu.clearCheck();
    }

    private synchronized void showReadBar() { // 显示工具栏
        showSystemBar();
        visible(mLlBottomMenu, mAblTopMenu);
        Animation animation = AnimationUtils.loadAnimation(mLlBottomMenu.getContext(), R.anim.push_bottom_in);
        mLlBottomMenu.startAnimation(animation);
        Animation animation1 = AnimationUtils.loadAnimation(mLlBottomMenu.getContext(), R.anim.push_top_in);
        mAblTopMenu.startAnimation(animation1);
    }

    public synchronized void toggleReadBar(boolean hideSystembar) { // 切换工具栏 隐藏/显示 状态
        if (isVisible(mAblTopMenu)) {
            hideReadBar(hideSystembar);
        } else {
            showReadBar();
        }
    }

    /**
     * 告诉后台当前阅读到第几章
     */
    private void notifyServerReadedChapter() {
        // 告诉后台读到第几章了
        if (mParams == null) {
            mParams = new ChapterRequestParams();
        }
        mParams.book_id = mBookId;
        mParams.content_id = mCurChapterId;
        mListPresenter.notifyServerReadedChapter(mParams);
    }

    private class SeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {
        private boolean mStartProgress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (mSeekbarLightness != null && seekBar.getId() == mSeekbarLightness.getId() && fromUser) { // 非自动调节模式下 才可调整屏幕亮度
                stopAutoLightness();
                DisplayUtils.setScreenBrightness(progress, AdBookReaderActivity.this);
                SettingManager.getInstance().saveReadBrightness(progress);
            } else if (mChapterSeekbar != null && seekBar.getId() == mChapterSeekbar.getId()) {
                Log.d("wcy", "start progress:" + seekBar.getProgress());
                if (seekBar.getId() == mChapterSeekbar.getId()) {
                    if (!mStartProgress) {
                        return;
                    }
                    ObtainAllSimpleChaptersHelper.getAllSimpleChapters(mBookId, new INetCommCallback<List<SimpleChapterBean>>() {
                        @Override
                        public void onResponse(List<SimpleChapterBean> list) {
                            if (mChapterProgressContainer == null) {
                                return;
                            }
                            if (!Utils.isEmptyList(list)) {
                                int progress = seekBar.getProgress();
                                int chapter = (progress * mPageLoader.getChapterCount()) / 100;
                                chapter = chapter - 1;
                                if (chapter >= list.size()) {
                                    chapter = list.size() - 1;
                                }
                                if (chapter >= mPageLoader.getChapterCount()) {
                                    chapter = mPageLoader.getChapterCount() - 1;
                                }
                                if (chapter < 0) {
                                    chapter = 0;
                                }
                                mSeekbarListenerPageCount = 0;
                                DisplayUtils.visible(mChapterProgressContainer);
                                mChapterProgressName.setText(list.get(chapter).title);
                                mChapterProgressPercent.setText(BookUtils.getReadProgress(String.valueOf(chapter > 0 ? chapter + 1 : 0), String.valueOf(mPageLoader.getChapterCount())));
                            }
                        }

                        @Override
                        public void onError(int code, String errDesc) {
                            DisplayUtils.gone(mChapterProgressContainer);
                        }
                    });
                }
            }
        }

        @Override
        public void onStartTrackingTouch(final SeekBar seekBar) {
            if (mChapterSeekbar != null && seekBar.getId() == mChapterSeekbar.getId()) {
                if (Utils.isEmptyList(ObtainAllSimpleChaptersHelper.getAllSimpleChaptersFromCache(mBookId))) {
                    String s = "正在加载章节数据，请稍后。";
                    if (mPageLoader.getPageStatus() == PageLoader.STATUS_OFFLINE) {
                        s = "书籍已下线";
                    }
                    ToastUtil.showMessage(s);
                    mStartProgress = false;
                    return;
                }
                // 先隐藏掉之间衔接广告
                DisplayUtils.gone(mAdBetweenChaptersLayout);
                mStartProgress = true;
            }
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (mChapterSeekbar != null && seekBar.getId() == mChapterSeekbar.getId()) {
                mStartProgress = false;
                // 处理阅读进度
                handleReadProgress(seekBar.getProgress());
            }
        }
    }

    private void startAutoLightness() {
        SettingManager.getInstance().saveAutoBrightness(true);
        DisplayUtils.startAutoBrightness(this);
        int value = (int) (DisplayUtils.getSystemBrightness(this) / 255f * 100);
        if (mSeekbarLightness != null) {
            mSeekbarLightness.setProgress(value);
        }
        DisplayUtils.setScreenBrightness(value, this);
        if (mCbAutoBrightness != null) {
            mCbAutoBrightness.setChecked(SettingManager.getInstance().isAutoBrightness());
        }
    }

    private void stopAutoLightness() {
        SettingManager.getInstance().saveAutoBrightness(false);
        DisplayUtils.stopAutoBrightness(this);
        int value = SettingManager.getInstance().getReadBrightness();
        if (mSeekbarLightness != null) {
            mSeekbarLightness.setProgress(value);
        }
        DisplayUtils.setScreenBrightness(value, AdBookReaderActivity.this);
        if (mCbAutoBrightness != null) {
            mCbAutoBrightness.setChecked(SettingManager.getInstance().isAutoBrightness());
        }
    }

    private class ChechBoxChangeListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (buttonView.getId() == mCbAutoBrightness.getId()) {
                // 修改亮度
                if (isChecked) {
                    startAutoLightness();
                } else {
                    stopAutoLightness();
                }
            } else if (buttonView.getId() == mCbEyeShield.getId()) {
                // 护眼模式
                SettingManager.getInstance().setEyeShieldMode(isChecked);
                mEyeShieldLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            } else if (buttonView.getId() == mNightMode.getId()) {
                isNightMode = isChecked;
                processClickDayNight();
            }
        }
    }

    /**
     * 调整到前一章
     */
    private void preChapter() {
        if (mCurChapterIndex <= 1) {
            ToastUtil.showMessage("已经到第一章了");
            return;
        }
        SimpleChapterBean info = SettingManager.getInstance().getSimpleChapterInfo(mBookId, mCurChapterIndex - 1);
        if (info != null) {
            mCurChapterIndex--;
            mCurChapterId = info.content_id;
            mStartRead = false;
            readCurrentChapter();
        } else {
            downloadSimpleChapter(mCurChapterIndex - 1);
        }
    }

    /**
     * 调整到下一章
     */
    private void nextChapter() {
        if (mCurChapterIndex >= mPageLoader.getChapterCount()) {
            ToastUtil.showMessage("已经到最后一章了");
            return;
        }
        SimpleChapterBean info = SettingManager.getInstance().getSimpleChapterInfo(mBookId, mCurChapterIndex + 1);
        if (info != null) {
            mCurChapterIndex++;
            mCurChapterId = info.content_id;
            mStartRead = false;
            readContentByNetOrLocal();
        } else {
            downloadSimpleChapter(mCurChapterIndex + 1);
        }
    }

    /**
     * 注册相关
     */
    private void register() {
        //注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, intentFilter);
        //eventbus register
        EventBus.getDefault().register(this);
        //监听屏幕亮度变化
        observeScreenLightness();
    }

    /**
     * 反注册相关
     */
    private void unregister() {
        unregisterReceiver(mReceiver);
        EventBus.getDefault().unregister(this);
        getContentResolver().unregisterContentObserver(mLightnessObserver);
    }

    /**
     * 获取banner广告
     */
    private void getAdBanner() {
        if (isFetchBannerAd) {
            mAdHeight = getResources().getDimensionPixelSize(R.dimen.px_150);
            AndroidSchedulers.mainThread().scheduleDirect(() -> {
                Log.e("evan", "阅读器下方banner调用广告");
                AdUtils.fetchAdUtil(this, mAdContainer, null, mAdPositionId, AdStyleBean.BANNER_STYLE, 0, this);
            }, 100, TimeUnit.MILLISECONDS);
        }
    }

    /**
     * 根据章节获取广告位置Id
     */
    private void getAdPosId() {
        ADConfigBean config5 = ADConfigs.showAD(String.valueOf(ADConfigBean.POSITION_BOOK_READER_BOTTOM_5));
        if (mCurChapterIndex > 0 && mCurChapterIndex % 5 == 0) {
            mAdPositionId = ADConfigBean.POSITION_BOOK_READER_BOTTOM_5;
            //判断章节5的倍数广告是否为空 且与每章节广告不同
            if (config5 == null) {
                mAdPositionId = ADConfigBean.POSITION_BOOK_READER_BOTTOM;
            }
            //判断章节5的倍数相邻两章切换广告 且与5倍数广告不同
        } else if ((mCurChapterIndex > 1 && mCurChapterIndex % 5 == 1) || (mCurChapterIndex > 1 && mCurChapterIndex % 5 == 4)) {
            mAdPositionId = ADConfigBean.POSITION_BOOK_READER_BOTTOM;
        } else {
            mAdPositionId = ADConfigBean.POSITION_BOOK_READER_BOTTOM;
        }
    }

    /**
     * 设置底部banner主题色
     */
    private void setAdBannerTheme() {
        if (mWrapAdContainer == null || mAdContainer == null) {
            return;
        }
        if (SettingManager.getInstance().isNight()) {
            mAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_night));
            mWrapAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_night));
            mAdBannerTrans.setBackgroundColor(getResources().getColor(R.color.ad_banner_trans));
            DisplayUtils.visible(mAdBannerTrans);
        } else {
            int readTheme = SettingManager.getInstance().getReadTheme();
            DisplayUtils.gone(mAdBannerTrans);
            switch (readTheme) {
                case ThemeManager.NORMAL:
                    mAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_white));
                    mWrapAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_white));
                    break;
                case ThemeManager.YELLOW:
                    mAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_yellow));
                    mWrapAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_yellow));
                    break;
                case ThemeManager.GRAY:
                    mAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_gray));
                    mWrapAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_gray));
                    break;
                case ThemeManager.GREEN:
                    mAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_green));
                    mWrapAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_green));
                    break;
                case ThemeManager.LEATHER:
                    mAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_leather));
                    mWrapAdContainer.setBackgroundColor(getResources().getColor(R.color.read_theme_leather));
                    break;
                case ThemeManager.NIGHT:
                    mAdContainer.setBackgroundColor(getResources().getColor(R.color.transparent));
                    mWrapAdContainer.setBackgroundColor(getResources().getColor(R.color.transparent));
                    break;
            }
        }
    }

    /**
     * 处理章节衔接广告
     *
     * @param chapter
     */
    private void processBetweenChaptersAd(int chapter) {
        int adType;
        if (chapter > 0 && chapter % 5 == 0) {
            mShowAD = ADConfigs.showAD(String.valueOf(ADConfigBean.POSITION_READER_BETWEEN_CHAPTER_5));
            adType = ADConfigBean.POSITION_READER_BETWEEN_CHAPTER_5;
            if (mShowAD == null) {
                mShowAD = ADConfigs.showAD(String.valueOf(ADConfigBean.POSITION_READER_BETWEEN_CHAPTER));
                adType = ADConfigBean.POSITION_READER_BETWEEN_CHAPTER;
            }
        } else {
            mShowAD = ADConfigs.showAD(String.valueOf(ADConfigBean.POSITION_READER_BETWEEN_CHAPTER));
            adType = ADConfigBean.POSITION_READER_BETWEEN_CHAPTER;
        }
        if (mShowAD == null) {
            return;
        }
        if (mAdBetweenChaptersLayout == null) {
            mAdBetweenChaptersLayout = new AdBetweenChaptersLayout(this);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            mRlBookReadRoot.addView(mAdBetweenChaptersLayout, params);
            gone(mAdBetweenChaptersLayout);
        }
        mAdBetweenChaptersLayout.refresh(mBookId, chapter, adType, isNightMode);
    }

    /**
     * 关闭广告 或者广告加载失败
     */
    private void closeAdBanner() {
        if (mLoadSuccShowAd) {
            // 设置全屏显示章节内容
            mPageLoader.setVisibleHeight(mScreenHeight);
            mAdHeight = 0;
            ThemeManager.setAdHeight(mAdHeight);
            int fontSizePx = SettingManager.getInstance().getReadFontSize();
            mPageLoader.setTextSize(fontSizePx);
            mLoadSuccShowAd = false;
            // 隐藏广告容器 以及 广告蒙层
            DisplayUtils.gone(mWrapAdContainer, mAdBannerTrans);
        }
    }

    /**
     * 获取底部banner和章节衔接之间的广告
     */
    private void acquireAd() {
        if (System.currentTimeMillis() - sClickTime1 < 1000) {
            return;
        }
        sClickTime1 = System.currentTimeMillis();
        Log.d("wcy", "acquireAd");
        // 获取底部bannerId
        getAdPosId();
        // 获取章节衔接之间的广告
        processBetweenChaptersAd(mCurChapterIndex);
        if (mReaderAdHelper != null) {
            mReaderAdHelper.showAdDialog();
        }
    }

    /**
     * 根据错误码处理阅读器页面
     *
     * @param code
     */
    private void handleBookError(int code) {
        if (mErrorLayout == null) {
            ViewStub stub = findViewById(R.id.err_stub);
            if (stub != null) {
                View v = stub.inflate();
                mErrorLayout = v.findViewById(R.id.err_handle_container);
            }
        }
        if (mErrorLayout != null) {
            mErrorLayout.setCallback(new ReadErrCallback() {
                @Override
                public void onRetry() {
                    mStartRead = false;
                    readContentByNetOrLocal();
                }

                @Override
                public void onTouch() {
                    toggleReadBar(true);
                }
            });
            mErrorLayout.refreshByErrorCode(code);
        }
    }

    /**
     * 刷新最近阅读数据(最近阅读)
     */
    private void refreshShelfData() {
        // 刷新最近阅读信息
        ShelfEvent event = new ShelfEvent(ShelfEvent.REFRESH_RECENT);
        EventBus.getDefault().post(event);
    }
}

